import { observable, action, asMap, toJS } from 'mobx';
import * as API from '../../apis/add'
import { SearchPage, Browser } from 'weaver-mobile-page';
import { forwardViewForm } from '../../util/common';
import { Tools, Bubble } from 'weaver-mobile'
const getLabel = Tools.getLabel;

export class AddStore {
    @observable hasTab = true;
    @observable datas = [];             //所有类型数据
    @observable datasM = [];             //模糊搜索到的类型数据

    @observable tabs = [];
    @observable isHasCom = false;          //是否配置了允许显示常用流程

    @observable dialogSwitch1 = observable.map ? observable.map({}) : asMap({});    //切换手风琴图标属性(我的收藏)
    @observable dialogSwitch2 = observable.map ? observable.map({}) : asMap({});    //切换手风琴图标属性（全部流程）
    @observable isFuzzy = false;             //是否处于模糊搜索状态       
    @observable page = -1;               //tab页的key
    // @observable user = "";  //创建身份的选择

    @observable resultDatas = {//带到form表单中的数据
        iscreate: '',//新建进入
        workflowid: '',//流程id
        isagent: '0',//是否是代理
        f_weaver_belongto_userid: '',//
        beagenter: '0',//代理人
        f_weaver_belongto_usertype: '0'
    }
    @observable searchPage = new SearchPage.Store({ route: '/add', id: "searchRecord" });
    @observable searchValue = "";
    searchValue_default = "";
    @observable activeKey3 = [];//全部流程中已打开的类型
    @observable activeKey2 = [];//搜藏的流程中已打开的类型
    @observable selectData = ""
    @observable abb = '1212';
    @observable isShowLoading = false;//跳转到表单详情页面前的loading
    queryParams = {};
    openByDefaultBrowser;

    parentURL = "/spa/workflow/static4mobile/index.html#/add";
    @observable loading = false;  //加载列表数据时的loading

    //身份选择
    @observable idSF = 0; //

    @observable browserStore = new Browser.Store({ route: '/add', id: "importWf" });

    @observable currentUser = {};

    mulitcol = 1;//pc端是否多列显示--默认值
    isAbc = 0;//pc端是否按照路径首字母排序显示--默认值

    @action
    inintDatas = (isRetainCondition) => {
        this.loading = true;
        if (isRetainCondition) {
            let retainCondition = Tools.ss.getJSONObj('__wf__list__add__retainCondition') || {};
            this.datas = retainCondition.datas;             //所有类型数据
            this.hasTab = retainCondition.hasTab;             //是否显示tab
            this.datasM = retainCondition.datasM;             //模糊搜索到的类型数据
            this.tabs = retainCondition.tabs;
            this.loading = false;
            this.isHasCom = retainCondition.isHasCom;          //是否配置了允许显示常用流程
            this.isFuzzy = retainCondition.isFuzzy;             //是否处于模糊搜索状态       
            this.page = retainCondition.page;               //tab页的key
            this.user = retainCondition.user;  //创建身份的选择
            this.resultDatas = retainCondition.resultDatas;
            this.searchValue = retainCondition.searchValue;
            this.activeKey3 = retainCondition.activeKey3;//全部流程中已打开的类型
            this.activeKey2 = retainCondition.activeKey2;//搜藏的流程中已打开的类型
            this.selectData = retainCondition.selectData;
            this.abb = retainCondition.abb;
            //身份选择
            this.idSF = 0; //
            this.searchPage = new SearchPage.Store({ route: '/add', id: "searchRecord" });
            this.browserStore = new Browser.Store({ route: '/add', id: "importWf" });
            this.searchPage.setState({ searchValue: retainCondition.searchValue })
            let dialogSwitch1 = retainCondition.dialogSwitch1 || {};    //切换手风琴图标属性(我的收藏)
            let dialogSwitch2 = retainCondition.dialogSwitch2 || {};    //切换手风琴图标属性(我的收藏)
            this.dialogSwitch1 = observable.map ? observable.map({}) : asMap({});    //切换手风琴图标属性(我的收藏)
            this.dialogSwitch2 = observable.map ? observable.map({}) : asMap({});    //切换手风琴图标属性（全部流程）
            this.queryParams = retainCondition.queryParams;
            for (let key in dialogSwitch1) {
                this.dialogSwitch1.set(key, dialogSwitch1[key])
            }
            for (let key in dialogSwitch2) {
                this.dialogSwitch2.set(key, dialogSwitch2[key])
            }
        } else {
            this.datas = [];             //所有类型数据
            this.datasM = [];             //模糊搜索到的类型数据
            this.tabs = [];
            this.isHasCom = false;          //是否配置了允许显示常用流程
            this.dialogSwitch1 = observable.map ? observable.map({}) : asMap({});    //切换手风琴图标属性(我的收藏)
            this.dialogSwitch2 = observable.map ? observable.map({}) : asMap({});    //切换手风琴图标属性（全部流程）
            this.isFuzzy = false;             //是否处于模糊搜索状态       
            //this.page = 0;               //tab页的key----store中有默认值
            this.user = "";  //创建身份的选择
            this.resultDatas = {//带到form表单中的数据
                iscreate: '',//新建进入
                workflowid: '',//流程id
                isagent: '0',//是否是代理
                f_weaver_belongto_userid: '',//
                beagenter: '0',//代理人
                f_weaver_belongto_usertype: '0'
            }
            this.searchPage = new SearchPage.Store({ route: '/add', id: "searchRecord" });
            this.searchValue = "";
            this.activeKey3 = [];//全部流程中已打开的类型
            this.activeKey2 = [];//搜藏的流程中已打开的类型
            this.selectData = ""
            this.abb = '1212';
            //身份选择
            this.idSF = 0; //
            this.browserStore = new Browser.Store({ route: '/add', id: "importWf" });
        }
    }

    setSS = () => {
        let retainCondition = {
            datas: this.datas,
            hasTab: this.hasTab,
            datasM: this.datasM,
            tabs: this.tabs,
            isHasCom: this.isHasCom,
            dialogSwitch1: toJS(this.dialogSwitch1),
            dialogSwitch2: toJS(this.dialogSwitch2),
            isFuzzy: this.isFuzzy,
            page: this.page,
            user: this.user,
            resultDatas: this.resultDatas,
            searchValue: this.searchValue_default,
            activeKey3: this.activeKey3,
            activeKey2: this.activeKey2,
            selectData: this.selectData,
            abb: this.abb,
            idSF: this.idSF,
            searchPage: this.searchPage.searchValue,
            queryParams: this.queryParams,
            // this.browserStore = new Browser.Store({ route: '/add', id: "importWf" });
        }
        Tools.ss.set('__wf__list__add__retainCondition', JSON.stringify(retainCondition));
    }

    @action("取得所有列表数据")
    getDatas(params = {}) {
        if (this.queryParams.hasOwnProperty("wfRange")) {
            params.wfRange = this.queryParams.wfRange;
        }
        this.loading=true;
        API.getDatas({ needall: 1, tabkey: 1, ...params, ...this.queryParams, ismobile: 1 }).then(result => {
            this.loading=false;
            this.datas = result.datas;
            this.datasM = result.datas;
            this.openByDefaultBrowser = result.openByDefaultBrowser;
            this.isHasCom = result.commonuse;
            if (result.hasOwnProperty("tabs")) {
                this.hasTab = true;
            } else {
                this.hasTab = false;
            }
            const pagetmp = result.userOperateHabit ? parseInt(result.userOperateHabit.defaultSelectedTab,0) : 0;//默认定位tab
            this.mulitcol = result.userOperateHabit ? result.userOperateHabit.mulitcol : 1;
            this.isAbc = result.userOperateHabit ? result.userOperateHabit.isAbc : 0;
            if (this.isHasCom === "1") {
                this.page = (pagetmp === 1 || pagetmp === 2) ? (pagetmp === 1 ? 2 : 1) : 0;//pc端保存的数据：全部==1；收藏==2；常用==3
                this.tabs = [
                    { title: getLabel(500430, '常用流程'), sub: '1',wfDefaultSelectedTabKey:'3' },
                    { title: getLabel(18030, '我的收藏'), sub: '2',wfDefaultSelectedTabKey:'2' },
                    { title: getLabel(84382, '全部流程'), sub: '3',wfDefaultSelectedTabKey:'1' },
                ];
            } else {
                this.page = pagetmp === 1 ? 1 : 0;//pc端保存的数据：全部==1；收藏==2；常用==3
                this.tabs = [
                    { title: getLabel(18030, '我的收藏'), sub: '1',wfDefaultSelectedTabKey:'2' },
                    { title: getLabel(84382, '全部流程'), sub: '2',wfDefaultSelectedTabKey:'1' },
                ];
            }
            this.currentUser = result.user;
        })
    }

    @action("更新收藏状态")
    doAddWfToColl(colected, typeId, id) {
        API.doAddWfToColl({ 'workflowid': id, "worktypeid": typeId, "needall": colected }).then(datas => {
            const { success = false } = datas;
            if (success) {
                if (colected === "1") {
                    Bubble.success(getLabel(386356, "加入收藏成功"), 2)
                } else if (colected === "0") {
                    Bubble.success(getLabel(386357, "取消收藏成功"), 2)
                }
                this.datasM.map(items => {
                    if (items.id === typeId) {
                        items.wfbeans.map(item => {
                            if (item.id === id) {
                                item.wfColl = colected;
                            }
                            return item;
                        })
                    }
                    return items;
                })
                this.datas.map(items => {
                    if (items.id === typeId) {
                        items.wfbeans.map(item => {
                            if (item.id === id) {
                                item.wfColl = colected;
                            }
                            return item;
                        })
                    }
                    return items;
                })
            }
        })
    }

    @action("修改store中的属性--公共方法")
    setState = (state = {}) => {
        const keys = Object.keys(state);
        keys.forEach(key => {
            if (Array.isArray(state[key])) {
                // this.activeKey3.clear();
                this[key].replace(state[key]);
            } else {
                this[key] = state[key]
            }
        })
    }

    @action("添加一个流程")
    requestImport = (params) => {
        this.isShowLoading = true;
        API.requestImport(params).then(datas => {
            // //跳到表单
            let urlParams = {
                requestid: datas.requestid.toString(),
            };
            if(this.openByDefaultBrowser == 1){
                urlParams.openByDefaultBrowser = this.openByDefaultBrowser
            }
            this.isShowLoading = false;
            this.setSS();
            forwardViewForm(urlParams, () => { }, "", this.parentURL); 
            this.browserStore.setState({ selectedKeys: [] })
        })
    }

    @action("控制列表是否打开的图标")
    changeAccordionIcon = (key, value, type) => {
        let dswitch = observable.map ? observable.map({}) : asMap({});
        key.map(k => dswitch.set(k, value))
        if (type === 2) {
            this.dialogSwitch1 = dswitch;
            this.activeKey2 = key
        } else if (type === 3) {
            this.dialogSwitch2 = dswitch;
            this.activeKey3 = key;
        }
    }

    setResultDatas = (state = {}) => {
        const keys = Object.keys(state);
        keys.forEach(key => {
            this.resultDatas[key] = state[key];
        })
    }

    saveLastSet = (params) => {
        const wfDefaultSelectedTabKey = 1;//记录最后一次选中的tab
        params['mulitcol'] = this.mulitcol;
        params['isAbc'] = this.isAbc;
        API.saveUserOperateHabit(params);
    }
}